package com.leetcode.concurrency;

import java.util.concurrent.Semaphore;

/**
 * @author Dennis Li
 * @date 2020/9/17 10:13
 */
public class DiningPhilosophers2 {

    // 用于标识左右的刀叉
    private final Semaphore[] forks;
    // 用于进入临界区
    private final Semaphore mutex;

    public DiningPhilosophers2() {
        mutex = new Semaphore(2);
        forks = new Semaphore[5];
        for (int i = 0; i < 5; i++) {
            forks[i] = new Semaphore(1);
        }
    }

    // call the run() method of any runnable to execute its code
    public void wantsToEat(int philosopher,
                           Runnable pickLeftFork,
                           Runnable pickRightFork,
                           Runnable eat,
                           Runnable putLeftFork,
                           Runnable putRightFork) throws InterruptedException {
        mutex.acquire();
        forks[philosopher].acquire();
        forks[(philosopher + 1) % 5].acquire();

        pickLeftFork.run();
        pickRightFork.run();
        mutex.release();

        eat.run();
        putLeftFork.run();
        putRightFork.run();
        forks[philosopher].release();
        forks[(philosopher + 1) % 5].release();
    }
}
